package com.zr.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.zr.util.JdbcUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 获取user对应的功能
 * @author 曾鹏
 *
 */
public class UserMethodDao {
	
    /**
     * 通过ID获取单一功能json数据格式
     * @param parentId
     * @return
     */
	public  JSONArray  getSMethodById(int parentId){
		JSONArray js = new JSONArray();
		String sql = "select * from function where  fparentid= ?";
		Connection con = JdbcUtil.getDBConnection();
		try {
			PreparedStatement pst = con.prepareStatement(sql);
			pst.setInt(1, parentId);
			ResultSet  rs = pst.executeQuery();
			while(rs.next()){
				JSONObject  jsobj = new JSONObject();
				jsobj.put("id", rs.getInt("fid"));
				jsobj.put("text", rs.getString("fname"));
				jsobj.put("state", rs.getString("fstate"));
				
				JSONObject  attrObj = new JSONObject();
				attrObj.put("url", rs.getString("fpath"));
				jsobj.put("attributes", attrObj);
				js.add(jsobj);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			JdbcUtil.closedConnection(con);
		}
		return js;
	}
	
	/**
	 * 获取所有的功能变为对应的json格式
	 * @param parentId
	 * @return   easyui树形需要的json格式
	 */
	public  JSONArray getAllMethodsById(int parentId){
		JSONArray js = this.getSMethodById(parentId);
		
		for (int i = 0; i < js.size(); i++) {
			JSONObject jsObj = js.getJSONObject(i);
			if("open".equals(jsObj.get("state"))){
				continue;
			}else{
				jsObj.put("children", getAllMethodsById(Integer.parseInt(jsObj.getString("id"))));
			}
		}
		
		return js;
	}

}
